{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "nbsphinx": "hidden"
   },
   "source": [
    "[Index](Index.ipynb) - [Back](Widget Styling.ipynb) - [Next](Widget Asynchronous.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Building a Custom Widget - Email widget"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The widget framework is built on top of the Comm framework (short for communication).  The Comm framework is a framework that allows the kernel to send/receive JSON messages to/from the front end (as seen below).\n",
    "\n",
    "![Widget layer](images/WidgetArch.png)\n",
    "\n",
    "To create a custom widget, you need to define the widget both in the browser and in the python kernel."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Building a Custom Widget"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get started, you'll create a simple email widget."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Python Kernel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### DOMWidget and Widget"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To define a widget, you must inherit from the Widget or DOMWidget base class.  If you intend for your widget to be displayed in the Jupyter notebook, you'll want to inherit from the DOMWidget.  The DOMWidget class itself inherits from the Widget class.  The Widget class is useful for cases in which the Widget is not meant to be displayed directly in the notebook, but instead as a child of another rendering environment.  For example, if you wanted to create a three.js widget (a popular WebGL library), you would implement the rendering window as a DOMWidget and any 3D objects or lights meant to be rendered in that window as Widgets."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### _view_name"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Inheriting from the DOMWidget does not tell the widget framework what front end widget to associate with your back end widget.\n",
    "\n",
    "Instead, you must tell it yourself by defining specially named trait attributes, `_view_name`, `_view_module`, and `_view_module_version` (as seen below) and optionally `_model_name` and `_model_module`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from traitlets import Unicode, Bool, validate, TraitError\n",
    "from ipywidgets import DOMWidget, register\n",
    "\n",
    "\n",
    "@register\n",
    "class Email(DOMWidget):\n",
    "    _view_name = Unicode('EmailView').tag(sync=True)\n",
    "    _view_module = Unicode('email_widget').tag(sync=True)\n",
    "    _view_module_version = Unicode('0.1.0').tag(sync=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### sync=True traitlets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Traitlets is an IPython library for defining type-safe properties on configurable objects.  For this tutorial you do not need to worry about the *configurable* piece of the traitlets machinery.   The `sync=True` keyword argument tells the widget framework to handle synchronizing that value to the browser.  Without `sync=True`, attributes of the widget won't be synchronized with the front-end."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Other traitlet types"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Unicode, used for `_view_name`, is not the only Traitlet type, there are many more some of which are listed below:  \n",
    "\n",
    "- Any\n",
    "- Bool\n",
    "- Bytes\n",
    "- CBool\n",
    "- CBytes\n",
    "- CComplex\n",
    "- CFloat\n",
    "- CInt\n",
    "- CLong\n",
    "- CRegExp\n",
    "- CUnicode\n",
    "- CaselessStrEnum\n",
    "- Complex\n",
    "- Dict\n",
    "- DottedObjectName\n",
    "- Enum\n",
    "- Float\n",
    "- FunctionType\n",
    "- Instance\n",
    "- InstanceType\n",
    "- Int\n",
    "- List\n",
    "- Long\n",
    "- Set\n",
    "- TCPAddress\n",
    "- Tuple\n",
    "- Type\n",
    "- Unicode\n",
    "- Union\n",
    "\n",
    "\n",
    "Not all of these traitlets can be synchronized across the network, only the JSON-able traits and Widget instances will be synchronized."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Front end (JavaScript)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Models and views"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The IPython widget framework front end relies heavily on [Backbone.js](http://backbonejs.org/).  Backbone.js is an MVC (model view controller) framework.  Widgets defined in the back end are automatically synchronized with generic Backbone.js models in the front end.  The traitlets are added to the front end instance automatically on first state push.  The `_view_name` trait that you defined earlier is used by the widget framework to create the corresponding Backbone.js view and link that view to the model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Import @jupyter-widgets/base"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You first need to import the `@jupyter-widgets/base` module. To import modules, use the `define` method of [require.js](http://requirejs.org/) (as seen below)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%javascript\n",
    "define('email_widget', [\"@jupyter-widgets/base\"], function(widgets) {\n",
    "    \n",
    "});"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Define the view"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, define your widget view class.  Inherit from the `DOMWidgetView` by using the `.extend` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%javascript\n",
    "require.undef('email_widget');\n",
    "\n",
    "define('email_widget', [\"@jupyter-widgets/base\"], function(widgets) {\n",
    "    \n",
    "    // Define the EmailView\n",
    "    var EmailView = widgets.DOMWidgetView.extend({\n",
    "        \n",
    "    });\n",
    "\n",
    "    return {\n",
    "        EmailView: EmailView\n",
    "    }\n",
    "});"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Render method"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Lastly, override the base `render` method of the view to define custom rendering logic.  A handle to the widget's default DOM element can be acquired via `this.el`.  The `el` property is the DOM element associated with the view."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%javascript\n",
    "require.undef('email_widget');\n",
    "\n",
    "define('email_widget', [\"@jupyter-widgets/base\"], function(widgets) {\n",
    "\n",
    "    var EmailView = widgets.DOMWidgetView.extend({\n",
    "\n",
    "        // Render the view.\n",
    "        render: function() { \n",
    "            this.email_input = document.createElement('input');\n",
    "            this.email_input.type = 'email';\n",
    "            this.email_input.value = 'example@example.com';\n",
    "            this.email_input.disabled = true;\n",
    "\n",
    "            this.el.appendChild(this.email_input); \n",
    "        },\n",
    "    });\n",
    "\n",
    "    return {\n",
    "        EmailView: EmailView\n",
    "    };\n",
    "});"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Test"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should be able to display your widget just like any other widget now."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Email()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Making the widget stateful"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There is not much that you can do with the above example that you can't do with the IPython display framework.  To change this, you will make the widget stateful.  Instead of displaying a static \"example@example.com\" email address, it will display an address set by the back end.  First you need to add a traitlet in the back end.  Use the name of `value` to stay consistent with the rest of the widget framework and to allow your widget to be used with interact."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We want to be able to avoid user to write an invalid email address, so we need a validator using traitlets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from traitlets import Unicode, Bool, validate, TraitError\n",
    "from ipywidgets import DOMWidget, register\n",
    "\n",
    "\n",
    "@register\n",
    "class Email(DOMWidget):\n",
    "    _view_name = Unicode('EmailView').tag(sync=True)\n",
    "    _view_module = Unicode('email_widget').tag(sync=True)\n",
    "    _view_module_version = Unicode('0.1.0').tag(sync=True)\n",
    "\n",
    "    # Attributes\n",
    "    value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n",
    "    disabled = Bool(False, help=\"Enable or disable user changes.\").tag(sync=True)\n",
    "\n",
    "    # Basic validator for the email value\n",
    "    @validate('value')\n",
    "    def _valid_value(self, proposal):\n",
    "        if proposal['value'].count(\"@\") != 1:\n",
    "            raise TraitError('Invalid email value: it must contain an \"@\" character')\n",
    "        if proposal['value'].count(\".\") == 0:\n",
    "            raise TraitError('Invalid email value: it must contain at least one \".\" character')\n",
    "        return proposal['value']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Accessing the model from the view"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To access the model associated with a view instance, use the `model` property of the view.  `get` and `set` methods are used to interact with the Backbone model.  `get` is trivial, however you have to be careful when using `set`.  After calling the model `set` you need call the view's `touch` method.  This associates the `set` operation with a particular view so output will be routed to the correct cell.  The model also has an `on` method, which allows you to listen to events triggered by the model (like value changes)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Rendering model contents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By replacing the string literal with a call to `model.get`, the view will now display the value of the back end upon display.  However, it will not update itself to a new value when the value changes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%javascript\n",
    "require.undef('email_widget');\n",
    "\n",
    "define('email_widget', [\"@jupyter-widgets/base\"], function(widgets) {\n",
    "    \n",
    "    var EmailView = widgets.DOMWidgetView.extend({\n",
    "\n",
    "        // Render the view.\n",
    "        render: function() { \n",
    "            this.email_input = document.createElement('input');\n",
    "            this.email_input.type = 'email';\n",
    "            this.email_input.value = this.model.get('value');\n",
    "            this.email_input.disabled = this.model.get('disabled');\n",
    "\n",
    "            this.el.appendChild(this.email_input);\n",
    "        },\n",
    "    });\n",
    "\n",
    "    return {\n",
    "        EmailView: EmailView\n",
    "    };\n",
    "});"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Email(value='john.doe@domain.com', disabled=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Dynamic updates"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get the view to update itself dynamically, register a function to update the view's value when the model's `value` property changes.  This can be done using the `model.on` method.  The `on` method takes three parameters, an event name, callback handle, and callback context.   The Backbone event named `change` will fire whenever the model changes.  By appending `:value` to it, you tell Backbone to only listen to the change event of the `value` property (as seen below)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%javascript\n",
    "require.undef('email_widget');\n",
    "\n",
    "define('email_widget', [\"@jupyter-widgets/base\"], function(widgets) {\n",
    "    \n",
    "    var EmailView = widgets.DOMWidgetView.extend({\n",
    "\n",
    "        // Render the view.\n",
    "        render: function() { \n",
    "            this.email_input = document.createElement('input');\n",
    "            this.email_input.type = 'email';\n",
    "            this.email_input.value = this.model.get('value');\n",
    "            this.email_input.disabled = this.model.get('disabled');\n",
    "\n",
    "            this.el.appendChild(this.email_input);\n",
    "            \n",
    "            // Python -> JavaScript update\n",
    "            this.model.on('change:value', this.value_changed, this);\n",
    "            this.model.on('change:disabled', this.disabled_changed, this);\n",
    "        },\n",
    "        \n",
    "        value_changed: function() {\n",
    "            this.email_input.value = this.model.get('value'); \n",
    "        },\n",
    "        \n",
    "        disabled_changed: function() {\n",
    "            this.email_input.disabled = this.model.get('disabled'); \n",
    "        },\n",
    "    });\n",
    "\n",
    "    return {\n",
    "        EmailView: EmailView\n",
    "    };\n",
    "});"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This allows us to update the value from the Python kernel to the views. Now to get the value updated from the front-end to the Python kernel (when the input is not disabled) we can do it using the `model.set` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%javascript\n",
    "require.undef('email_widget');\n",
    "\n",
    "define('email_widget', [\"@jupyter-widgets/base\"], function(widgets) {\n",
    "    \n",
    "    var EmailView = widgets.DOMWidgetView.extend({\n",
    "\n",
    "        // Render the view.\n",
    "        render: function() { \n",
    "            this.email_input = document.createElement('input');\n",
    "            this.email_input.type = 'email';\n",
    "            this.email_input.value = this.model.get('value');\n",
    "            this.email_input.disabled = this.model.get('disabled');\n",
    "\n",
    "            this.el.appendChild(this.email_input);\n",
    "            \n",
    "            // Python -> JavaScript update\n",
    "            this.model.on('change:value', this.value_changed, this);\n",
    "            this.model.on('change:disabled', this.disabled_changed, this);\n",
    "            \n",
    "            // JavaScript -> Python update\n",
    "            this.email_input.onchange = this.input_changed.bind(this);\n",
    "        },\n",
    "        \n",
    "        value_changed: function() {\n",
    "            this.email_input.value = this.model.get('value'); \n",
    "        },\n",
    "        \n",
    "        disabled_changed: function() {\n",
    "            this.email_input.disabled = this.model.get('disabled'); \n",
    "        },\n",
    "        \n",
    "        input_changed: function() {\n",
    "            this.model.set('value', this.email_input.value);\n",
    "            this.model.save_changes();\n",
    "        },\n",
    "    });\n",
    "\n",
    "    return {\n",
    "        EmailView: EmailView\n",
    "    };\n",
    "});"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "email = Email(value='john.doe@domain.com', disabled=False)\n",
    "email"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "email.value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "email.value = 'jane.doe@domain.com'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## More advanced uses: Packaging and distributing Jupyter widgets\n",
    "\n",
    "A template project is available in the form of a cookie cutter: https://github.com/jupyter/widget-cookiecutter\n",
    "\n",
    "This project is meant to help custom widget authors get started with the packaging and the distribution of Jupyter interactive widgets.\n",
    "\n",
    "It produces a project for a Jupyter interactive widget library following the current best practices for using interactive widgets. An implementation for a placeholder \"Hello World\" widget is provided."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbsphinx": "hidden"
   },
   "source": [
    "[Index](Index.ipynb) - [Back](Widget Styling.ipynb) - [Next](Widget Asynchronous.ipynb)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
